package com.yanftch.jsonformat.json2ets.views;

import javax.swing.*;
import java.awt.event.*;

public class SetGetChooseDialog extends JDialog {
    private JPanel contentPane;
    private JButton btnCancel;
    private JButton btnOk;
    private OnButtonClickListener mOnButtonClickListener;

    public SetGetChooseDialog() {
        setContentPane(contentPane);
        setModal(true);
        setSize(400, 300);
        setLocationRelativeTo(null);
        getRootPane().setDefaultButton(btnCancel);

        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        if (mOnButtonClickListener != null) {
            mOnButtonClickListener.isConfirm(true);
        }
        dispose();
    }

    private void onCancel() {
        if (mOnButtonClickListener != null) {
            mOnButtonClickListener.isConfirm(false);
        }
        dispose();
    }

    public void setOnButtonClickListener(OnButtonClickListener l) {
        mOnButtonClickListener = l;
    }

    public interface OnButtonClickListener {
        void isConfirm(boolean isConfirm);
    }

    public static void main(String[] args) {
        SetGetChooseDialog dialog = new SetGetChooseDialog();
        dialog.pack();
        dialog.setVisible(true);
        System.exit(0);
    }
}
